package com.tangcco.lockwell.service.impl;

import com.tangcco.lockwell.domain.DataDictionary;
import com.tangcco.lockwell.domain.ExamPaper;
import com.tangcco.lockwell.domain.file.*;
import com.tangcco.lockwell.service.DataDictionaryService;
import com.tangcco.lockwell.service.subjectFileService;
import com.tangcco.lockwell.context.WebContext;
import com.tangcco.lockwell.domain.Article;
import com.tangcco.lockwell.viewmodel.admin.exam.ExamPaperEditRequestVM;
import com.tangcco.lockwell.viewmodel.admin.exam.ExamPaperTitleItemVM;
import com.tangcco.lockwell.viewmodel.admin.question.QuestionEditRequestVM;
import com.tangcco.lockwell.viewmodel.admin.question.QuestionVMUpdate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.tangcco.lockwell.utility.DateToString.dateToString;
import static com.tangcco.lockwell.utility.JsonUtil.*;

@Service
public class subjectFileServiceImpl implements subjectFileService {
    @Resource
    protected WebContext webContext;

    @Resource
    private ArticleServiceImpl articleService;

    @Resource
    private QuestionServiceImpl questionService;

    @Resource
    private DataDictionaryService dataDictionaryService;

    @Resource
    private ExamPaperServiceImpl examPaperService;

    @Override
    public int politicsUpdate(String jsonContent, String type,String name) {
        QuestionVMUpdate questionVMUpdate = new QuestionVMUpdate();
        List<QuestionJsonFile> questionJsonFiles = toJsonListObject(jsonContent, QuestionJsonFile.class);
        ExamPaperEditRequestVM examPaperEditRequestVM = new ExamPaperEditRequestVM();
        ExamPaperTitleItemVM examPaperTitleItemVM = new ExamPaperTitleItemVM();
        List<ExamPaperTitleItemVM> examPaperTitleItemVMs = new ArrayList<>();
        List<QuestionEditRequestVM> questionEditRequestVMs = new ArrayList<>();
        examPaperEditRequestVM.setSubjectId(2);
        examPaperEditRequestVM.setName(name+"_"+type+"_"+"试卷");
        for (QuestionJsonFile questionJsonFile : questionJsonFiles) {
            DataDictionary dataDictionary1 = dataDictionaryService.selectById(questionJsonFile.getQuestion_type());
            if (!dataDictionary1.getCategoryName().equals(examPaperTitleItemVM.getName())) {
                if (examPaperTitleItemVM.getName() != null){
                    examPaperTitleItemVM.setQuestionItems(questionEditRequestVMs);
                    examPaperTitleItemVMs.add(examPaperTitleItemVM);
                    examPaperTitleItemVM = new ExamPaperTitleItemVM();
                    questionEditRequestVMs = new ArrayList<>();
                    examPaperTitleItemVM.setName(dataDictionary1.getCategoryName());
                }
                examPaperTitleItemVM.setName(dataDictionary1.getCategoryName());
            }

            if (questionJsonFile.getQuestion_type() == 26){
                questionVMUpdate.setScore(1);
            }else if (questionJsonFile.getQuestion_type() == 27){
                questionVMUpdate.setScore(2);
            }else if (questionJsonFile.getQuestion_type() == 28){
                questionVMUpdate.setScore(10);
            }
            questionVMUpdate.setQuestionTypeId(questionJsonFile.getQuestion_type());
            questionVMUpdate.setSubjectParentId(2);
            Pattern pattern = Pattern.compile("^\\d+$");
            if (type != null && type != "") {
                String[] split = type.split("-");
                DataDictionary dataDictionary = new DataDictionary();
                if (split.length > 0) {
                if (split.length > 1) {
                    if (split[0]!= null && split[0]!= "" && isNumeric(split[0])){
                        questionVMUpdate.setGradeLevel(Integer.valueOf(split[0]));
                        examPaperEditRequestVM.setLevel(Integer.valueOf(split[0]));
                    }
                    dataDictionary.setCategoryName(split[1]);
                    examPaperEditRequestVM.setPaperType(33);
                }else if (isNumeric(split[0])){
                    questionVMUpdate.setGradeLevel(Integer.valueOf(split[0]));
                    examPaperEditRequestVM.setLevel(Integer.valueOf(split[0]));
                    examPaperEditRequestVM.setPaperType(33);
                }else {
                    dataDictionary.setCategoryName(split[0]);
                    examPaperEditRequestVM.setPaperType(34);
                }}
                if (dataDictionary.getCategoryName() != null && dataDictionary.getCategoryName()!= "") {
                    List<DataDictionary> dataDictionaries = dataDictionaryService.dataDictionarySelective(dataDictionary);
                    questionVMUpdate.setSubjectId(dataDictionaries.get(0).getId());
                }
            }

            // 答案
            char c = 'A';
            String answer = "";
            if (questionJsonFile.getCorrectAnswer().length() <= 1) {
                if (questionJsonFile.getCorrectAnswer() != "") {
                    c = (char) (Integer.valueOf(questionJsonFile.getCorrectAnswer()) + 65);
                    answer = String.valueOf(c);
                }
            } else {
                String[] split = questionJsonFile.getCorrectAnswer().split(",");
                for (int i = 0; i < split.length; i++) {
                    c = (char) (Integer.valueOf(split[i]) + 65);
                    if (i != split.length - 1) {
                        answer += String.valueOf(c) + ",";
                    } else {
                        answer += String.valueOf(c);
                    }
                }
            }
            String sortedAnswer = Arrays.stream(answer.split(","))
                    .sorted()
                    .collect(Collectors.joining(","));
            questionVMUpdate.setCorrect(sortedAnswer);

            List<QuestionTwoFile> questionTwoFiles = new ArrayList<QuestionTwoFile>();
            List<QuestionOneFile> questionOneFiles = new ArrayList<QuestionOneFile>();
            Article article = new Article();
            // 1 单选 2 多选
            if (questionJsonFile.getQuestion_type() == 26 || questionJsonFile.getQuestion_type() == 27) {
                char num = 'A';
                QuestionOneFile questionOneFile = new QuestionOneFile();
                for (String option : questionJsonFile.getOptions()) {
                    QuestionTwoFile questionTwoFile = new QuestionTwoFile();
                    questionTwoFile.setPrefix(String.valueOf(num));
                    questionTwoFile.setContent(option);
                    num++;
                    questionTwoFiles.add(questionTwoFile);
                }
                questionOneFile.setItem(questionTwoFiles);
                questionOneFile.setQtitle(questionJsonFile.getQuestion_title());
                questionOneFiles.add(questionOneFile);
            }
            // 15 问答
            if (questionJsonFile.getQuestion_type() == 28) {
                String[] split = questionJsonFile.getQuestion_title().split("\\+");
                if (split.length >= 3){
                article.setArticleContent(split[0]);
                article.setCreateTime(dateToString(new Date()));
                articleService.insert(article);
                questionVMUpdate.setArticleId(article.getArticleId());
                for (int i = 1; i < split.length; i++) {
                    QuestionOneFile questionOneFile = new QuestionOneFile();
                    questionOneFile.setQtitle(split[i]);
                    questionOneFiles.add(questionOneFile);
                }
                }else {
                    for (int i = 0; i < split.length; i++) {
                        QuestionOneFile questionOneFile = new QuestionOneFile();
                        questionOneFile.setQtitle(split[i]);
                        questionOneFiles.add(questionOneFile);
                    }
                }
            }
            questionVMUpdate.setTextContent(toJsonStr(questionOneFiles));
            questionVMUpdate.setCreateUserId(webContext.getCurrentUser().getUserId());
            questionVMUpdate.setStatus(2);
            questionVMUpdate.setCreateTime(dateToString(new Date()));
            questionService.insertQuestion(questionVMUpdate);
            QuestionEditRequestVM questionEditRequestVM = new QuestionEditRequestVM();
            questionEditRequestVM.setId(questionVMUpdate.getId());
            questionEditRequestVMs.add(questionEditRequestVM);

        }
        examPaperTitleItemVM.setQuestionItems(questionEditRequestVMs);
        examPaperTitleItemVMs.add(examPaperTitleItemVM);
        examPaperEditRequestVM.setTitleItems(examPaperTitleItemVMs);
        examPaperService.savePaperFromVM(examPaperEditRequestVM, webContext.getCurrentUser());
        return 1;
    }

    @Override
    public int englishUpdate(String jsonContent, String type,String name) {
        QuestionVMUpdate questionVMUpdate = new QuestionVMUpdate();
        questionVMUpdate.setSubjectParentId(2);
        questionVMUpdate.setStatus(1);
        ExamPaperEditRequestVM examPaperEditRequestVM = new ExamPaperEditRequestVM();
        ExamPaperTitleItemVM examPaperTitleItemVM = new ExamPaperTitleItemVM();
        List<ExamPaperTitleItemVM> examPaperTitleItemVMs = new ArrayList<>();
        List<QuestionEditRequestVM> questionEditRequestVMs = new ArrayList<>();
        examPaperEditRequestVM.setSubjectId(2);
        examPaperEditRequestVM.setName(name+"_"+type+"_"+"试卷");
        if (type != null && type != "") {
            String[] split = type.split("-");
            DataDictionary dataDictionary = new DataDictionary();
            dataDictionary.setCategoryName(split[1]);
            List<DataDictionary> dataDictionaries = dataDictionaryService.dataDictionarySelective(dataDictionary);
            questionVMUpdate.setSubjectId(dataDictionaries.get(0).getId());
            if (split[1] != null && split[1] != "") {
                questionVMUpdate.setGradeLevel(Integer.valueOf(split[0]));
                examPaperEditRequestVM.setLevel(Integer.valueOf(split[0]));
                examPaperEditRequestVM.setPaperType(33);
            }else {
                examPaperEditRequestVM.setPaperType(34);
            }
        }
        EnglishJsonFile englishJsonFile = toJsonObject(jsonContent, EnglishJsonFile.class);
        // 除作文以外的题型
        for (EnglishOneFile material : englishJsonFile.getMaterials()) {
            DataDictionary dataDictionary1 = dataDictionaryService.selectById(material.getType());
            if (!dataDictionary1.getCategoryName().equals(examPaperTitleItemVM.getName())) {
                if (examPaperTitleItemVM.getName() != null){
                    examPaperTitleItemVM.setQuestionItems(questionEditRequestVMs);
                    examPaperTitleItemVMs.add(examPaperTitleItemVM);
                    examPaperTitleItemVM = new ExamPaperTitleItemVM();
                    questionEditRequestVMs = new ArrayList<>();
                    examPaperTitleItemVM.setName(dataDictionary1.getCategoryName());
                }
                examPaperTitleItemVM.setName(dataDictionary1.getCategoryName());
            }
            questionVMUpdate.setQuestionTypeId(material.getType());
            Article article = new Article();
            String articleContent = "";
            if (material.getType() == 20 || material.getType() == 22 || material.getType() == 40) {
                questionVMUpdate.setScore(10);
            }else if (material.getType() == 21) {
                if (questionVMUpdate.getSubjectId() == 4) {
                    questionVMUpdate.setScore(10);
                }else if (questionVMUpdate.getSubjectId() == 5) {
                    questionVMUpdate.setScore(15);
                }
            }
            //  材料
            for (EnglishTwoFile englishTwoFile : material.getContent()) {
                if (englishTwoFile.getValue() != null) {
                    // 判断是否有图片
                    String s = englishTwoFile.getValue().get(englishTwoFile.getValue().size() - 1);
                    String s1 = s.split(":")[0];
                    // 有图片
                    if (s1.equals("https")) {
                        questionVMUpdate.setPicture(s);
                        for (int i = 0; i < englishTwoFile.getValue().size() - 1; i++) {
                            articleContent += englishTwoFile.getValue().get(i) + "\n";
                        }
                    } else {
                        for (String option : englishTwoFile.getValue()) {
                            articleContent += option + "\n";
                        }
                    }
                    article.setArticleContent(articleContent);
                    article.setCreateTime(dateToString(new Date()));
                    articleService.insert(article);
                    questionVMUpdate.setArticleId(article.getArticleId());
                }
            }
            //  题目
            String answer = "";

            List<QuestionOneFile> questionOneFiles = new ArrayList<QuestionOneFile>();
            for (QuestionJsonFile questionJsonFile : material.getQuestions()) {
                // 答案
                char c = 'A';
                int num = 1;
                if (questionJsonFile.getCorrectAnswer() != "") {
                    c = (char) (Integer.valueOf(questionJsonFile.getCorrectAnswer()) + 65);
                    if (num != material.getQuestions().size()) {
                        answer += String.valueOf(c) + ",";
                    } else {
                        answer += String.valueOf(c);
                    }
                }
                num++;
                // 题干
                char num1 = 'A';
                List<QuestionTwoFile> questionTwoFiles = new ArrayList<QuestionTwoFile>();
                QuestionOneFile questionOneFile = new QuestionOneFile();
                for (String option : questionJsonFile.getOptions()) {
                    QuestionTwoFile questionTwoFile = new QuestionTwoFile();
                    questionTwoFile.setPrefix(String.valueOf(num1));
                    questionTwoFile.setContent(option);
                    num1++;
                    questionTwoFiles.add(questionTwoFile);
                }
                questionOneFile.setItem(questionTwoFiles);
                questionOneFile.setQtitle(questionJsonFile.getQuestion_title());
                questionOneFiles.add(questionOneFile);
            }
            questionVMUpdate.setTextContent(toJsonStr(questionOneFiles));
            if (answer.endsWith(",")) {
                answer = answer.substring(0, answer.length() - 1);
            }
            questionVMUpdate.setCorrect(answer);
            questionVMUpdate.setCreateUserId(webContext.getCurrentUser().getUserId());
            questionVMUpdate.setCreateTime(dateToString(new Date()));
            questionService.insertQuestion(questionVMUpdate);
            QuestionEditRequestVM questionEditRequestVM = new QuestionEditRequestVM();
            questionEditRequestVM.setId(questionVMUpdate.getId());
            questionEditRequestVMs.add(questionEditRequestVM);
        }
        // 作文
        for (EnglishSanFile material : englishJsonFile.getWriting()) {
            DataDictionary dataDictionary1 = dataDictionaryService.selectById(material.getType());
            if (!dataDictionary1.getCategoryName().equals(examPaperTitleItemVM.getName())) {
                if (examPaperTitleItemVM.getName() != null){
                    examPaperTitleItemVM.setQuestionItems(questionEditRequestVMs);
                    examPaperTitleItemVMs.add(examPaperTitleItemVM);
                    examPaperTitleItemVM = new ExamPaperTitleItemVM();
                    questionEditRequestVMs = new ArrayList<>();
                    examPaperTitleItemVM.setName(dataDictionary1.getCategoryName());
                }
                examPaperTitleItemVM.setName(dataDictionary1.getCategoryName());
            }
            questionVMUpdate.setQuestionTypeId(material.getType());
            Article article = new Article();
            String articleContent = "";
            for (EnglishTwoFile englishTwoFile : material.getContent()) {
                if (englishTwoFile.getValue() != null) {
                    // 判断是否有图片
                    String s = englishTwoFile.getValue().get(englishTwoFile.getValue().size() - 1);
                    String s1 = s.split(":")[0];
                    // 有图片
                    if (s1.equals("https")) {
                        questionVMUpdate.setPicture(s);
                        for (int i = 0; i < englishTwoFile.getValue().size() - 1; i++) {
                            articleContent += englishTwoFile.getValue().get(i) + "\n";
                        }
                    } else {
                        for (String option : englishTwoFile.getValue()) {
                            articleContent += option + "\n";
                        }
                    }
                    article.setArticleContent(articleContent);
                    article.setCreateTime(dateToString(new Date()));
                    articleService.insert(article);
                    questionVMUpdate.setArticleId(article.getArticleId());
                }
                if (material.getType() == 23) {
                    questionVMUpdate.setScore(10);
                }else if (material.getType() == 24) {
                    if (questionVMUpdate.getSubjectId() == 4){
                        questionVMUpdate.setScore(20);
                    }else if (questionVMUpdate.getSubjectId() == 5) {
                        questionVMUpdate.setScore(15);
                    }
                }
                questionVMUpdate.setTextContent("[]");
                questionService.insertQuestion(questionVMUpdate);
                QuestionEditRequestVM questionEditRequestVM = new QuestionEditRequestVM();
                questionEditRequestVM.setId(questionVMUpdate.getId());
                questionEditRequestVMs.add(questionEditRequestVM);
            }
        }
        examPaperTitleItemVM.setQuestionItems(questionEditRequestVMs);
        examPaperTitleItemVMs.add(examPaperTitleItemVM);
        examPaperEditRequestVM.setTitleItems(examPaperTitleItemVMs);
        examPaperService.savePaperFromVM(examPaperEditRequestVM, webContext.getCurrentUser());

        return 0;
    }


    public static boolean isNumeric(String strNum) {
        return strNum.matches("\\d+");
    }
}
